<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="react 基础语法使用, 杜顺">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>react 基础语法使用 | 杜顺</title>
    <link rel="icon" type="image/png" href="/ds/medias/logo1.png">

    <link rel="stylesheet" type="text/css" href="/ds/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/ds/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/ds/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/ds/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/ds/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/ds/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/ds/css/my.css">

    <script src="/ds/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.1.1"><link rel="alternate" href="/ds/atom.xml" title="杜顺" type="application/atom+xml">
<link rel="stylesheet" href="/ds/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/ds/" class="waves-effect waves-light">
                    
                    <img src="/ds/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">杜顺</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/ds/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/ds/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">杜顺</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/ds/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ds/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ds/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ds/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ds/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/ds/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/ds/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">react 基础语法使用</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/ds/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/ds/tags/js/">
                                <span class="chip bg-color">js</span>
                            </a>
                        
                            <a href="/ds/tags/react/">
                                <span class="chip bg-color">react</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/ds/categories/react/" class="post-category">
                                react
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-05-01
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    13 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="react-基础语法使用"><a href="#react-基础语法使用" class="headerlink" title="react 基础语法使用"></a>react 基础语法使用</h1><p>　　刚开始不久react，在菜鸟上及其他前辈网站上学习，下面开始我的自学笔记。</p>
<p>　　包括：</p>
<ul>
<li>渲染元素</li>
<li>组件（函数方法定义、es6 class定义）</li>
<li>事件处理</li>
<li>条件渲染</li>
<li>列表</li>
</ul>
<p>　　下面代码部分将不会再写html部分，html部分如下：</p>
<pre><code>&lt;div id="example"&gt;&lt;/div&gt;</code></pre>
<p>　　多余的话不多说，具体如下：</p>
<ul>
<li><strong>渲染元素(函数方法，es6方式)</strong><ul>
<li>　函数方法</li>
</ul>
</li>
</ul>
<pre><code>function Clock(props) {
  return (
    &lt;div&gt;
      &lt;h1&gt;Hello, world!&lt;/h1&gt;
      &lt;h2&gt;现在是 {props.date.toLocaleTimeString()}.&lt;/h2&gt;
    &lt;/div&gt;
  );
}

function tick() {
  ReactDOM.render(
    &lt;Clock date={new Date()} /&gt;,
    document.getElementById('example')
  );
}

setInterval(tick, 1000);</code></pre>
<ul>
<li><ul>
<li>es6方法</li>
</ul>
</li>
</ul>
<pre><code>class Clock extends React.Component {
  render() {
    return (
      &lt;div&gt;
        &lt;h1&gt;Hello, world!&lt;/h1&gt;
        &lt;h2&gt;现在是 {this.props.date.toLocaleTimeString()}.&lt;/h2&gt;
      &lt;/div&gt;
    );
  }
}

function tick() {
  ReactDOM.render(
    &lt;Clock date={new Date()} /&gt;,
    document.getElementById('example')
  );
}

setInterval(tick, 1000);</code></pre>
<ul>
<li><strong>组件</strong></li>
</ul>
<p>　　1、我们可以使用函数定义一个组件：</p>
<pre><code>function HelloMessage(props) {
    return &lt;h1&gt;Hello World!&lt;/h1&gt;;
}</code></pre>
<p>　　也可以使用ES6 class来定义一个组件：</p>
<pre><code>class Welcome extends React.Component {
  render() {
    return &lt;h1&gt;Hello World!&lt;/h1&gt;;
  }
}</code></pre>
<p>　　2.需要向组件传递参数，可以使用this.props对象</p>
<pre><code>function HelloMessage(props) {
    return &lt;h1&gt;Hello {props.name}!&lt;/h1&gt;;
}

const element = &lt;HelloMessage name="Runoob"/&gt;;

ReactDOM.render(
    element,
    document.getElementById('example')
);</code></pre>
<p>　　注意：在添加属性时，class属性需要写成className,for属性需要写成htmlFor，这是因为class和for是JavaScript的保留字。</p>
<p>　　复合组件</p>
<p>　　可以通过创建多个组件来合成一个组件，即把组件的不同功能点进行分离。</p>
<pre><code>&lt;script type="text/babel"&gt;
function Name(props) {
    return &lt;h1&gt;名称：{props.name}&lt;/h1&gt;;
}
function Url(props) {
    return &lt;h1&gt;地址：{props.url}&lt;/h1&gt;;
}
function Nickname(props) {
    return &lt;h1&gt;小名：{props.nickname}&lt;/h1&gt;;
}
function App() {
    return (
    &lt;div&gt;
        &lt;Name name="Tom" /&gt;
        &lt;Url url="https://www.cnblogs.com/freedom-feng/" /&gt;
        &lt;Nickname nickname="Jack" /&gt;
    &lt;/div&gt;
    );
}

ReactDOM.render(
     &lt;App /&gt;,
    document.getElementById('example')
);
&lt;/script&gt;</code></pre>
<ul>
<li><strong>事件</strong></li>
</ul>
<p>　　使用 ES6 class 语法来定义一个组件的时候，事件处理器会成为类的一个方法(推荐方式)。例如，下面的 Toggle 组件渲染一个让用户切换开关状态的按钮：</p>
<pre><code>class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // 这边绑定是必要的，这样 `this` 才能在回调函数中使用
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState =&gt; ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      &lt;button onClick={this.handleClick}&gt;
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      &lt;/button&gt;
    );
  }
}

ReactDOM.render(
  &lt;Toggle /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　注意：类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined。</p>
<p>　　如果上面使用 bind 让你很烦，这里有两种方式可以解决。如果你正在使用实验性的属性初始化器语法，你可以使用属性初始化器来正确的绑定回调函数：</p>
<pre><code>&lt;script type="text/babel"&gt;
class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () =&gt; {
    console.log('this is:', this);
  }

  render() {
    return (
      &lt;button onClick={this.handleClick}&gt;
        Click me
      &lt;/button&gt;
    );
  }
}
ReactDOM.render(
  &lt;LoggingButton /&gt;,
  document.getElementById('example')
);
&lt;/script&gt;</code></pre>
<p>　　如果你没有使用属性初始化器语法，你可以在回调函数中使用 箭头函数：</p>
<pre><code>class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      &lt;button onClick={(e) =&gt; this.handleClick(e)}&gt;
        Click me
      &lt;/button&gt;
    );
  }
}</code></pre>
<ul>
<li><ul>
<li>事件传参</li>
</ul>
</li>
</ul>
<pre><code>&lt;button onClick={(e) =&gt; this.deleteRow(id, e)}&gt;Delete Row&lt;/button&gt;
&lt;button onClick={this.deleteRow.bind(this, id)}&gt;Delete Row&lt;/button&gt;</code></pre>
<p>　　上面两种方式是等价的。</p>
<p>　　在例子中，参数e作为时间对象将被作为第二个参数进行传递。通过箭头函数的方式，事件对象必须显式的进行传递，但是通过bind的方式，时间对象以及更多的参数将会被隐式的进行传递。</p>
<p>　　注意：通过bind方式向监听函数传参，在类组件中定义的监听函数，事件对象e要排在所传参数的后面，例如：</p>
<pre><code>&lt;script type="text/babel"&gt;
class Popper extends React.Component{
    constructor(){
        super();
        this.state = {name:'Hello world!'};
    }

    preventPop(name, e){    //事件对象e要放在最后
        e.preventDefault();
        alert(name);
    }

    render(){
        return (
            &lt;div&gt;
                &lt;p&gt;hello&lt;/p&gt;
                {/* 通过 bind() 方法传递参数。 */}
                &lt;button onClick={this.preventPop.bind(this,this.state.name)}&gt;Click&lt;/button&gt;
            &lt;/div&gt;
        );
    }
}

ReactDOM.render(
  &lt;Popper /&gt;,
  document.getElementById('example')
);
&lt;/script&gt;</code></pre>
<ul>
<li><strong>条件渲染</strong></li>
</ul>
<p>　　先看两个组件：</p>
<pre><code>function UserGreeting(props) {
  return &lt;h1&gt;欢迎回来!&lt;/h1&gt;;
}

function GuestGreeting(props) {
  return &lt;h1&gt;请先注册。&lt;/h1&gt;;
}</code></pre>
<p>　　创建一个 Greeting 组件，它会根据用户是否登录来显示其中之一：</p>
<pre><code>function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return &lt;UserGreeting /&gt;;
  }
  return &lt;GuestGreeting /&gt;;
}

ReactDOM.render(
  // 尝试修改 isLoggedIn={true}:
  &lt;Greeting isLoggedIn={false} /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　<strong>元素变量</strong></p>
<p>　　可以使用变量来储存元素。它可以帮助你有条件的渲染组件的一部分，而输出的其他部分不会更改。</p>
<p>　　在下面的例子中，我们将要创建一个名为 LoginControl 的有状态的组件。</p>
<p>　　它会根据当前的状态来渲染 <loginbutton> 或 <logoutbutton>，它也将渲染前面例子中的 <greeting>。</greeting></logoutbutton></loginbutton></p>
<pre><code>class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;

    let button = null;
    if (isLoggedIn) {
      button = &lt;LogoutButton onClick={this.handleLogoutClick} /&gt;;
    } else {
      button = &lt;LoginButton onClick={this.handleLoginClick} /&gt;;
    }

    return (
      &lt;div&gt;
        &lt;Greeting isLoggedIn={isLoggedIn} /&gt;
        {button}
      &lt;/div&gt;
    );
  }
}

ReactDOM.render(
  &lt;LoginControl /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　<strong>与运算符 &amp;&amp;</strong></p>
<p>　　用花括号包裹代码在 JSX 中嵌入任何表达式 ，也包括 JavaScript 的逻辑与 &amp;&amp;，它可以方便地条件渲染一个元素。</p>
<pre><code>&lt;script type="text/babel"&gt;
function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    &lt;div&gt;
      &lt;h1&gt;Hello!&lt;/h1&gt;
      {unreadMessages.length &gt; 0 &amp;&amp;
        &lt;h2&gt;
          您有 {unreadMessages.length} 条未读信息。
        &lt;/h2&gt;
      }
    &lt;/div&gt;
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
  &lt;Mailbox unreadMessages={messages} /&gt;,
  document.getElementById('example')
);
&lt;/script&gt;　　</code></pre>
<p>　　在 JavaScript 中，true &amp;&amp; expression 总是返回 <strong>expression</strong>，而 false &amp;&amp; expression 总是返回 <strong>false</strong>。</p>
<p>　　因此，如果条件是 <strong>true</strong>，&amp;&amp; 右侧的元素就会被渲染，如果是 <strong>false</strong>，React 会忽略并跳过它。</p>
<p>　　<strong>三目运算符</strong></p>
<p>　　条件渲染的另一种方法是使用 JavaScript 的条件运算符:</p>
<pre><code>render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    &lt;div&gt;
      {isLoggedIn ? (
        &lt;LogoutButton onClick={this.handleLogoutClick} /&gt;
      ) : (
        &lt;LoginButton onClick={this.handleLoginClick} /&gt;
      )}
    &lt;/div&gt;
  );
}</code></pre>
<p>　　<strong>阻止组件渲染</strong></p>
<p>　　在极少数情况下，你可能希望隐藏组件，即使它被其他组件渲染。让 render 方法返回 null 而不是它的渲染结果即可实现。</p>
<p>　　在下面的例子中，<warningbanner> 根据属性 warn 的值条件渲染。如果 warn 的值是 false，则组件不会渲染：</warningbanner></p>
<pre><code>function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }

  return (
    &lt;div className="warning"&gt;
      警告!
    &lt;/div&gt;
  );
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showWarning: true}
    this.handleToggleClick = this.handleToggleClick.bind(this);
  }

  handleToggleClick() {
    this.setState(prevState =&gt; ({
      showWarning: !prevState.showWarning
    }));
  }

  render() {
    return (
      &lt;div&gt;
        &lt;WarningBanner warn={this.state.showWarning} /&gt;
        &lt;button onClick={this.handleToggleClick}&gt;
          {this.state.showWarning ? '隐藏' : '显示'}
        &lt;/button&gt;
      &lt;/div&gt;
    );
  }
}

ReactDOM.render(
  &lt;Page /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　组件的 render 方法返回 null 并不会影响该组件生命周期方法的回调。例如，componentWillUpdate 和 componentDidUpdate 依然可以被调用。</p>
<ul>
<li><strong>列表</strong></li>
</ul>
<p>　　使用JavaScript的map()方法来创建列表</p>
<pre><code>const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) =&gt;
  &lt;li&gt;{numbers}&lt;/li&gt;
);

ReactDOM.render(
  &lt;ul&gt;{listItems}&lt;/ul&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　可以将以上实例重构成一个组件，组件接收数组参数，每个列表元素分配一个 key，不然会出现警告 a key should be provided for list items，意思就是需要包含 key：</p>
<pre><code>function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =&gt;
    &lt;li key={number.toString()}&gt;
      {number}
    &lt;/li&gt;
  );
  return (
    &lt;ul&gt;{listItems}&lt;/ul&gt;
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  &lt;NumberList numbers={numbers} /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　<strong>keys</strong></p>
<p>　　Keys 可以在 DOM 中的某些元素被增加或删除的时候帮助 React 识别哪些元素发生了变化。因此你应当给数组中的每一个元素赋予一个确定的标识。</p>
<pre><code>const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =&gt;
  &lt;li key={number.toString()}&gt;
    {number}
  &lt;/li&gt;
);</code></pre>
<p>　　一个元素的 key 最好是这个元素在列表中拥有的一个独一无二的字符串。通常，我们使用来自数据的 id 作为元素的 key:</p>
<pre><code>const todoItems = todos.map((todo) =&gt;
  &lt;li key={todo.id}&gt;
    {todo.text}
  &lt;/li&gt;
);</code></pre>
<p>　　当元素没有确定的 id 时，你可以使用他的序列号索引 index 作为 key：</p>
<pre><code>const todoItems = todos.map((todo, index) =&gt;
  // 只有在没有确定的 id 时使用
  &lt;li key={index}&gt;
    {todo.text}
  &lt;/li&gt;
);</code></pre>
<p>　　如果列表可以重新排序，不建议使用索引来进行排序，因为这会导致渲染变得很慢。</p>
<p>　　<strong>用key提取组件</strong></p>
<p>　　元素的 key 只有在它和它的兄弟节点对比时才有意义。</p>
<p>　　错误示范：</p>
<pre><code>function ListItem(props) {
  const value = props.value;
  return (
    // 错啦！你不需要在这里指定key:
    &lt;li key={value.toString()}&gt;
      {value}
    &lt;/li&gt;
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =&gt;
    //错啦！元素的key应该在这里指定：
    &lt;ListItem value={number} /&gt;
  );
  return (
    &lt;ul&gt;
      {listItems}
    &lt;/ul&gt;
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  &lt;NumberList numbers={numbers} /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　key正确使用方式：</p>
<pre><code>function ListItem(props) {
  // 对啦！这里不需要指定key:
  return &lt;li&gt;{props.value}&lt;/li&gt;;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =&gt;
    // 又对啦！key应该在数组的上下文中被指定
    &lt;ListItem key={number.toString()}
              value={number} /&gt;

  );
  return (
    &lt;ul&gt;
      {listItems}
    &lt;/ul&gt;
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  &lt;NumberList numbers={numbers} /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　在 map() 方法的内部调用元素时，最好随时记得为每一个元素加上一个独一无二的 key。</p>
<p>　　<strong>元素的key在他的兄弟元素之间应该唯一</strong></p>
<p>　　数组元素中使用的 key 在其兄弟之间应该是独一无二的。然而，它们不需要是全局唯一的。当我们生成两个不同的数组时，我们可以使用相同的键。</p>
<pre><code>function Blog(props) {
  const sidebar = (
    &lt;ul&gt;
      {props.posts.map((post) =&gt;
        &lt;li key={post.id}&gt;
          {post.title}
        &lt;/li&gt;
      )}
    &lt;/ul&gt;
  );
  const content = props.posts.map((post) =&gt;
    &lt;div key={post.id}&gt;
      &lt;h3&gt;{post.title}&lt;/h3&gt;
      &lt;p&gt;{post.content}&lt;/p&gt;
    &lt;/div&gt;
  );
  return (
    &lt;div&gt;
      {sidebar}
      &lt;hr /&gt;
      {content}
    &lt;/div&gt;
  );
}

const posts = [
  {id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
  {id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
  &lt;Blog posts={posts} /&gt;,
  document.getElementById('example')
);</code></pre>
<p>　　key 会作为给 React 的提示，但不会传递给你的组件。如果您的组件中需要使用和 key 相同的值，请将其作为属性传递：</p>
<pre><code>const content = posts.map((post) =&gt;
  &lt;Post
    key={post.id}
    id={post.id}
    title={post.title} /&gt;
);</code></pre>
<p>　　上面例子中，Post 组件可以读出 props.id，但是不能读出 props.key。</p>
<p>　　<strong>在jsx中嵌入map()</strong></p>
<p>　　在上面的例子中，我们声明了一个单独的 listItems 变量并将其包含在 JSX 中:</p>
<pre><code>function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =&gt;
    &lt;ListItem key={number.toString()}
              value={number} /&gt;

  );
  return (
    &lt;ul&gt;
      {listItems}
    &lt;/ul&gt;
  );
}</code></pre>
<p>　　JSX 允许在大括号中嵌入任何表达式，所以我们可以在 map() 中这样使用：</p>
<pre><code>function NumberList(props) {
  const numbers = props.numbers;
  return (
    &lt;ul&gt;
      {numbers.map((number) =&gt;
        &lt;ListItem key={number.toString()}
                  value={number} /&gt;

      )}
    &lt;/ul&gt;
  );
}</code></pre>
<p>　　这么做有时可以使你的代码更清晰，但有时这种风格也会被滥用。就像在 JavaScript 中一样，何时需要为了可读性提取出一个变量，这完全取决于你。但请记住，如果一个 map() 嵌套了太多层级，那你就可以提取出组件。</p>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/ds/about" rel="external nofollow noreferrer">杜顺</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://dusun.gitee.io/ds/ds/2019/05/01/react-ji-chu-yu-fa-shi-yong/">https://dusun.gitee.io/ds/ds/2019/05/01/react-ji-chu-yu-fa-shi-yong/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/ds/about" target="_blank">杜顺</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/ds/tags/js/">
                                    <span class="chip bg-color">js</span>
                                </a>
                            
                                <a href="/ds/tags/react/">
                                    <span class="chip bg-color">react</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/ds/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/ds/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/ds/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/ds/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/ds/2019/05/17/vuex-shua-xin-ye-mian-shu-ju-diu-shi-wen-ti/">
                    <div class="card-image">
                        
                        
                        <img src="/ds/medias/featureimages/1.jpg" class="responsive-img" alt="vuex刷新页面数据丢失问题">
                        
                        <span class="card-title">vuex刷新页面数据丢失问题</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            vuex刷新页面数据丢失问题解决思路：在项目中，登录后，通过登录接口会获取到很多用户信息，首先将用户信息保存在vuex的store中，同时将这些信息也保存在sessionStorage中。这里需要注意的是vuex中的变量是响应式的，而ses
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-05-17
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/ds/categories/vue/" class="post-category">
                                    vue
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/ds/tags/js/">
                        <span class="chip bg-color">js</span>
                    </a>
                    
                    <a href="/ds/tags/vuex/">
                        <span class="chip bg-color">vuex</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/ds/2019/04/22/jquery-chang-yong-fang-fa/">
                    <div class="card-image">
                        
                        
                        <img src="/ds/medias/featureimages/18.jpg" class="responsive-img" alt="jQuery常用方法">
                        
                        <span class="card-title">jQuery常用方法</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            jQuery常用方法取值与赋值操作
$("#ID").val(); //取value值
$("#ID").val("xxx"); //赋值
$("#ID").text(); //相当于取innerText
$("#ID").text("")
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-04-22
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/ds/categories/js/" class="post-category">
                                    js
                                </a>
                            
                            <a href="/ds/categories/js/jquery/" class="post-category">
                                    jquery
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/ds/tags/js/">
                        <span class="chip bg-color">js</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/ds/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/ds/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/ds/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/ds/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/ds/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2018</span>
            <a href="/ds/about" target="_blank">杜顺</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">22.9k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:1404898412@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1404898412" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1404898412" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/e-e-89-49-49" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/e-e-89-49-49" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/ds/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/ds/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/ds/libs/materialize/materialize.min.js"></script>
    <script src="/ds/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/ds/libs/aos/aos.js"></script>
    <script src="/ds/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/ds/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/ds/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/ds/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/ds/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/ds/libs/background/canvas-nest.js"></script>
    

    

    
    <script type="text/javascript" src="/ds/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/ds/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
